package com.jia.train.global.web.handler;

import com.jia.train.global.exception.BusinessException;
import com.jia.train.global.response.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public BaseResponse<Void> handleException(BusinessException e) {
        BaseResponse<Void> response = new BaseResponse<Void>();
        logger.error("业务异常：{}", e.getMessage());
        response.setSuccess(false);
        response.setMessage(e.getBusinessEnum().getDesc());
        return response;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public BaseResponse<Void> handleException(RuntimeException e) {
        throw e;
    }


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public BaseResponse<Void> handleException(BindException e) {
        BaseResponse<Void> response = new BaseResponse<Void>();
        logger.error("参数校验异常：{}", e.getBindingResult().getAllErrors());
        response.setSuccess(false);
        response.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return response;
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResponse<Void> handleException(Exception e) throws Exception {
//        logger.info("seata 全局事务id：{}", RootContext.getXID());
//        if (StringUtils.hasText(RootContext.getXID())) {
//            throw e;
//        }
        BaseResponse<Void> response = new BaseResponse<Void>();
        logger.error("系统异常：{}", e.getMessage());
        response.setSuccess(false);
        response.setMessage("系统出现异常 请联系管理员");
        return response;
    }
}
